package priv.pfz.paxos.role;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import priv.pfz.paxos.network.dto.AcceptReq;
import priv.pfz.paxos.network.dto.AcceptResp;
import priv.pfz.paxos.network.dto.PrepareReq;
import priv.pfz.paxos.network.dto.PrepareResp;

/**
 * @author pengfangzhou
 * @date 2022/2/14 2:01
 */
@Slf4j
public class Acceptor {
    @Getter
    private String acceptorId;
    private int minProposal = -1;
    private String acceptedValue;
    private Integer acceptedProposalId;

    public Acceptor(String acceptorId) {
        this.acceptorId = acceptorId;
    }

    public PrepareResp handlePrepare(PrepareReq req) {
        if (req.getProposalId() <= minProposal) {
            return null;
        }
        minProposal = req.getProposalId();
        PrepareResp resp = new PrepareResp();
        resp.setAcceptedValue(acceptedValue);
        resp.setAcceptedProposalId(acceptedProposalId);
        return resp;
    }

    public AcceptResp handleAccept(AcceptReq req) {
        if (req.getProposalId() < minProposal) {
            return null;
        }
        minProposal = req.getProposalId();
        acceptedProposalId = req.getProposalId();
        acceptedValue = req.getValue();
        AcceptResp resp = new AcceptResp();
        resp.setMinProposal(minProposal);
        return resp;
    }
}
